package com.fj.netty.chat.handler;

import com.fj.netty.chat.message.LoginRequestMessage;
import com.fj.netty.chat.message.LoginResponseMessage;
import com.fj.netty.chat.server.service.ServiceFactory;
import com.fj.netty.chat.server.service.UserService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author fj
 * @date 2024/1/12 13:41
 */
@Slf4j
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        log.debug("收到消息：{}", msg);
        LoginResponseMessage message;
        UserService userService = ServiceFactory.getUserService();
        if (userService.login(msg.getUsername(), msg.getPassword())) {
            //登录成功
            ServiceFactory.getSession().bind(ctx.channel(), msg.getUsername());
            message = new LoginResponseMessage(true, "登录成功");
        } else {
            //登录失败
            message = new LoginResponseMessage(false, "用户名密码错误");
        }
        ctx.writeAndFlush(message);
    }
}
